今天來解YKL09(UVA10931):Parity
這題是dec轉成binary
計算binary總共有幾個1
用mod去解
#include <iostream>
using namespace std;
string dectobin(int I){
string str= "";
if(I==0)return "0";
if(I==1)return "1";
while(I > 0){
int md=0;
md = I % 2;
I = I / 2;
str = to_string(md) + str;
}
return str;
}
int main(){
int I;
while(cin >> I){
string str = dectobin(I);
if(I == 0) break;
int count=0;
for(int i=0;i <= str.size();i++ ){
if(str[i] == '1'){
count++;
}
}
cout << "The parity of " << str << " is " << count << " (mod 2)." << endl;
}
return 0;
}